package cn.hxzy.teacher.service.impl;


import cn.hxzy.common.domain.ClassMenu;
import cn.hxzy.common.domain.ClassTable;
import cn.hxzy.common.domain.User;
import cn.hxzy.common.domain.vo.ClassStudentVo;
import cn.hxzy.common.domain.vo.SelectClass;
import cn.hxzy.teacher.mapper.*;
import cn.hxzy.common.response.R;
import cn.hxzy.teacher.service.TeacherService;
import cn.hxzy.common.util.ThreadLocalUtil;
import cn.hxzy.user.mapper.ClassMenuMapper;
import cn.hxzy.user.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author LiDong
 * @Description
 * @create 2024/6/22 15:09
 */
@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private ClassMapper classTableMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassMenuMapper classMenuMapper;

    @Autowired
    private SelectClassMapper selectClassMapper;

    @Override
    public boolean createClassroom(ClassTable classTable) {
        int insert = classTableMapper.insert(classTable);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    /**
     * 根据班级名称查询班级
     *
     * @param className
     * @return
     */
    @Override
    public int selectOneClass(String className) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("class_name", className);
        ClassTable classTable = classTableMapper.selectOne(queryWrapper);
        if (classTable != null) {
            return 1;
        }
        return 0;
    }

    /**
     * 根据教师Id查询班级
     *
     * @param teacherId
     * @return
     */
    @Override
    public List<SelectClass> findClassroomByTeacherId(Integer teacherId) {
        List<ClassTable> classList = classTableMapper.selectList(new QueryWrapper<ClassTable>()
                .eq("create_id", teacherId));
        List<SelectClass> list = new ArrayList<>();
        classList.forEach(arr->{
            SelectClass selectClass = new SelectClass();
            String createName = selectClassMapper.getCreateNameById(teacherId);
            Integer studentNum =userMapper.selectUserCount(arr.getClassId());
            Integer courseNum = selectClassMapper.getCourseNum(arr.getClassId());
            selectClass.setCreateName(createName);
            selectClass.setClassName(arr.getClassName());
            selectClass.setId(arr.getClassId());
            selectClass.setStudentNum(studentNum);
            selectClass.setCourseNum(courseNum);
            list.add(selectClass);
        });
        return list;
    }

    /**
     * 根据班级Id修改班级名称
     *
     * @param classId
     * @param className
     * @return
     */
    @Override
    public String updateClass(Integer classId, String className) {
        int i = classTableMapper.updateClass(classId, className);
        if (i > 0) {
            return "修改成功";
        }
        return "修改失败";
    }

    //删除班级
    @Override
    public Boolean deleteClassroom(Long classroomId) {
        int i = classTableMapper.deleteById(classroomId);
        if (i > 0) return true;
        return false;
    }


    /**
     * 模糊查询班级
     *
     * @param name
     * @return
     */
    @Override
    public List<SelectClass> findClassroomByName(String name, Integer teacherId) {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        name="%"+name+"%";
        List<ClassTable> classList = classTableMapper.selectClass(name,teacherId);
        List<SelectClass> list = new ArrayList<>();
        classList.forEach(arr->{
            SelectClass selectClass = new SelectClass();
            String createName = selectClassMapper.getCreateNameById(teacherId);
            Integer studentNum =userMapper.selectUserCount(arr.getClassId());
            Integer courseNum = selectClassMapper.getCourseNum(arr.getClassId());
            selectClass.setCreateName(createName);
            selectClass.setClassName(arr.getClassName());
            selectClass.setId(arr.getClassId());
            selectClass.setStudentNum(studentNum);
            selectClass.setCourseNum(courseNum);
            list.add(selectClass);
        });
        return list;
    }

    @Override
    public List<ClassTable> findAllClassroom() {
        return classTableMapper.findAll();
    }


    @Override
    public List<ClassStudentVo> selectAllClassList(Integer courseId) {
        User user = ThreadLocalUtil.getUser();
        if(ObjectUtils.isEmpty(user)){
            throw new RuntimeException("用户信息为空");
        }
        QueryWrapper<ClassTable> classTableQueryWrapper = new QueryWrapper<>();
        List<ClassTable> classTables=null;
        if(!ObjectUtils.isEmpty(user.getSchoolId())){
            classTableQueryWrapper.eq("school_id",user.getSchoolId());
             classTables = classTableMapper.selectList(classTableQueryWrapper);
        }
        if(classTables.size() == 0){
            throw new RuntimeException("该学校没有班级");
        }
        List<ClassStudentVo>  classStudentVos=classTables.stream().map(classTable -> {
            ClassStudentVo classStudentVo = new ClassStudentVo();
            BeanUtils.copyProperties(classTable,classStudentVo);
            if(!StringUtils.isEmpty(classTable.getCreateId())){
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("user_id",classTable.getCreateId());
                userQueryWrapper.eq("user_type","2");
                User userName = userMapper.selectById(classTable.getCreateId());
                classStudentVo.setCreatorName(userName.getNickName());
                classStudentVo.setCreateId(userName.getUserId());
            }
            if(!StringUtils.isEmpty(classTable.getClassId())){
               Integer userCount = userMapper.selectUserCount(classTable.getClassId());
                classStudentVo.setStudentNumber(userCount);

            }
            //判断课程是否授权
            QueryWrapper<ClassMenu> classMenuQueryWrapper = new QueryWrapper<>();
            classMenuQueryWrapper.eq("class_id",classTable.getClassId());
            classMenuQueryWrapper.eq("course_id",courseId);
            Integer i = classMenuMapper.selectCount(classMenuQueryWrapper);
            if(i > 0){
                classStudentVo.setIsAuthorized(true);
            }else{
                classStudentVo.setIsAuthorized(false);
            }
            return classStudentVo;
        }).filter(classStudentVo -> user.getUserId()==classStudentVo.getCreateId()).collect(Collectors.toList());
        return classStudentVos;
    }

    @Override
    public List<ClassStudentVo> selectClassBySearchKey(Integer courseId, String className, String createName, Integer isAuthorized) {
        List<ClassStudentVo> classStudentVos = selectAllClassList(courseId);

        if (StringUtils.isEmpty(className) && StringUtils.isEmpty(createName) && (isAuthorized == -1)) {
            // 如果所有参数都为空或 null，则返回原始列表
            return classStudentVos;
        }

        // 根据不同的条件组合进行过滤
        return classStudentVos.stream()
                .filter(classStudentVo -> {
                    boolean matchesClassName = StringUtils.isEmpty(className) || classStudentVo.getClassName().contains(className);
                    boolean matchesCreateName = StringUtils.isEmpty(createName) || classStudentVo.getCreatorName().contains(createName);
                    boolean matchesIsAuthorized = (isAuthorized == -1) || (isAuthorized == 1 && classStudentVo.getIsAuthorized()) || (isAuthorized == 0 && !classStudentVo.getIsAuthorized());

                    // 只要有一个条件满足即可通过过滤
                    return matchesClassName && matchesCreateName && matchesIsAuthorized;
                })
                .collect(Collectors.toList());
    }

    @Override
    public R createClassroomCourseAuthorized(String courseId, String classId, Boolean isAuthorized) {
        if (isAuthorized) {
            QueryWrapper<ClassMenu> classMenuQueryWrapper = new QueryWrapper<>();
            classMenuQueryWrapper.eq("class_id", classId);
            classMenuQueryWrapper.eq("course_id", courseId);
            List<ClassMenu> classMenus = classMenuMapper.selectList(classMenuQueryWrapper);
            if (classMenus.size() == 0) {
                ClassMenu classMenu = new ClassMenu();
                classMenu.setClassId(Integer.valueOf(classId));
                classMenu.setCourseId(Integer.valueOf(courseId));
                classMenuMapper.insert(classMenu);
            }
        } else {
             classMenuMapper.delete(new QueryWrapper<ClassMenu>().eq("class_id", classId).eq("course_id", courseId));
        }
        return R.success("操作成功");
    }


}
